<script setup lang="ts">
import { useI18n } from "vue-i18n";
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { $t, transformI18n } from "@/plugins/i18n";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount, watch } from "vue";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";

import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import globalization from "@/assets/svg/globalization.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import Check from "@iconify-icons/ep/check";
import User from "@iconify-icons/ri/user-3-fill";

import HeaderView from "@/components/header/index.vue";

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const loginDay = ref(30);
const checked = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { t } = useI18n();
const { dataTheme, overallStyle, dataThemeChange } = useDataThemeChange();
dataThemeChange(overallStyle.value);
const { title, getDropdownItemStyle, getDropdownItemClass } = useNav();
const { locale, translationCh, translationEn } = useTranslationLang();

const ruleForm = reactive({
  username: "admin",
  password: "admin123"
});

const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      useUserStoreHook()
        .loginByUsername({ username: ruleForm.username, password: "admin123" })
        .then(res => {
          if (res.success) {
            // 获取后端路由
            return initRouter().then(() => {
              router.push(getTopMenu(true).path).then(() => {
                message(t("login.pureLoginSuccess"), { type: "success" });
              });
            });
          } else {
            message(t("login.pureLoginFail"), { type: "error" });
          }
        })
        .finally(() => (loading.value = false));
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (["Enter", "NumpadEnter"].includes(code)) {
    onLogin(ruleFormRef.value);
  }
}

watch(checked, bool => {
  useUserStoreHook().SET_ISREMEMBERED(bool);
});
watch(loginDay, value => {
  useUserStoreHook().SET_LOGINDAY(value);
});

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <!-- <img :src="bg" class="wave" /> -->
    <div class="flex-c absolute right-5 top-3">
      <!-- <!== 主题 ==>
      <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      /> -->
      <!-- <!== 国际化 ==>
      <el-dropdown trigger="click">
        <globalization
          class="hover:text-primary hover:!bg-[transparent] w-[20px] h-[20px] ml-1.5 cursor-pointer outline-none duration-300"
        />
        <template #dropdown>
          <el-dropdown-menu class="translation">
            <el-dropdown-item
              :style="getDropdownItemStyle(locale, 'zh')"
              :class="['dark:!text-white', getDropdownItemClass(locale, 'zh')]"
              @click="translationCh"
            >
              <IconifyIconOffline
                v-show="locale === 'zh'"
                class="check-zh"
                :icon="Check"
              />
              简体中文
            </el-dropdown-item>
            <el-dropdown-item
              :style="getDropdownItemStyle(locale, 'en')"
              :class="['dark:!text-white', getDropdownItemClass(locale, 'en')]"
              @click="translationEn"
            >
              <span v-show="locale === 'en'" class="check-en">
                <IconifyIconOffline :icon="Check" />
              </span>
              English
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown> -->
    </div>
    <!-- <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-none" />
          </Motion>

          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: transformI18n($t('login.pureUsernameReg')),
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  clearable
                  :placeholder="t('login.pureUsername')"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  clearable
                  show-password
                  :placeholder="t('login.purePassword')"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-button
                class="w-full mt-4"
                size="default"
                type="primary"
                :loading="loading"
                @click="onLogin(ruleFormRef)"
              >
                {{ t("login.pureLogin") }}
              </el-button>
            </Motion>
          </el-form>
        </div>
      </div>
    </div> -->

    <div class="login_container">
      <HeaderView :isTitle="false" />
      <div class="login_centbox">
        <div class="login_cent_left">
          <div class="login_line" />
          <div class="login_title">欢迎来到</div>
          <div class="login_title">ABB智慧用电管控平台</div>
          <div class="login_subtitle">
            智慧用电，智控未来 —— 打造安全高效能源新体验
          </div>
          <div class="login_module">
            <div class="login_module_list">
              <div class="login_list_left">
                <img src="@/assets/images/ico_list1.png" alt="可视化大屏" />
              </div>
              <div class="login_list_right">
                <div>可视化大屏</div>
                <div>数据呈现直观一目了然</div>
              </div>
            </div>
            <div class="login_module_list">
              <div class="login_list_left">
                <img src="@/assets/images/ico_list2.png" alt="能效监控" />
              </div>
              <div class="login_list_right">
                <div>能效监控</div>
                <div>实时能耗监测节能减排</div>
              </div>
            </div>
            <div class="login_module_list">
              <div class="login_list_left">
                <img src="@/assets/images/ico_list3.png" alt="设备管理" />
              </div>
              <div class="login_list_right">
                <div>设备管理</div>
                <div>优化设备运维提高效率</div>
              </div>
            </div>
            <div class="login_module_list">
              <div class="login_list_left">
                <img src="@/assets/images/ico_list4.png" alt="分析报表" />
              </div>
              <div class="login_list_right">
                <div>分析报表</div>
                <div>提供深度分析精准决策</div>
              </div>
            </div>
          </div>
        </div>
        <div class="login_cent_right">
          <div class="login_cent_formtitle">登录您的平台账号</div>
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: transformI18n($t('login.pureUsernameReg')),
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  clearable
                  :placeholder="t('login.pureUsername')"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  clearable
                  show-password
                  :placeholder="t('login.purePassword')"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-form-item>
                <div class="w-full h-[20px] flex justify-between items-center">
                  <el-checkbox v-model="checked">
                    <span class="flex">记住密码</span>
                  </el-checkbox>
                </div>
                <el-button
                  class="w-full mt-12"
                  size="default"
                  type="primary"
                  :loading="loading"
                  @click="onLogin(ruleFormRef)"
                >
                  {{ t("login.pureLogin") }}
                </el-button>
              </el-form-item>
            </Motion>
          </el-form>
        </div>
      </div>
      <div class="login_foot">
        <div>© 版权所有2024 ABB</div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.translation {
  ::v-deep(.el-dropdown-menu__item) {
    padding: 5px 40px;
  }

  .check-zh {
    position: absolute;
    left: 20px;
  }

  .check-en {
    position: absolute;
    left: 20px;
  }
}

.login_container {
  position: fixed;
  top: 76px;
  width: 100vw;
  height: calc(100vh - 76px);
  background-color: #fff;
  background-image: url("@/assets/images/img_login_bg.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100% 100%;

  .login_centbox {
    position: absolute;
    top: 50%;
    left: 50%;
    display: flex;
    // width: 68%;
    width: 60%;
    padding: 82px 1% 76px;
    background-image: url("@/assets/images/img_loginbox_bg.png");
    background-repeat: no-repeat;
    background-size: 100% 100%;
    border-radius: 5px;
    // background: #ffffff;
    box-shadow: 3px 0 21px 0 rgba($color: #000, $alpha: 2%);
    transform: translate(-50%, -50%);

    .login_cent_left {
      flex: 1;
      width: 50%;
      // padding: 0 93px;
      padding: 0 4%;

      .login_line {
        width: 67px; //4em;
        height: 4px;
        margin-bottom: 15px;
        background-color: var(--main-color);
      }

      .login_title {
        padding: 5px 0;
        font-size: 36px;
        font-weight: bold;
        line-height: 36px;
        color: #000;
        text-wrap: nowrap;
      }

      .login_subtitle {
        margin-top: 23px;
        font-size: 14px;
        font-weight: bold;
        line-height: 14px;
        color: #000;
      }

      .login_module {
        margin-top: 74px;

        .login_module_list {
          display: flex;
          align-items: first baseline;
          padding-bottom: 30px;

          .login_list_left {
            width: 18px;
            height: 17px;
            margin-right: 21px;

            img {
              width: 100%;
              max-width: 100%;
            }
          }

          .login_list_right {
            margin-top: -15px;
            font-size: 18px;
            line-height: 18px;
            color: #000;

            div:nth-child(2) {
              padding-top: 10px;
              font-size: 14px;
              font-weight: bold;
              line-height: 14px;
              color: #333;
            }
          }
        }
      }
    }

    .login_cent_right {
      flex: 1;
      width: 50%;
      // padding: 84px 116px 0;
      padding: 84px 4% 0;
      border-left: 1px solid var(--main-color);

      .login_cent_formtitle {
        margin-bottom: 55px;
        font-size: 24px;
        line-height: 24px;
        color: #333;
      }
    }

    .el-input {
      :deep(.el-input__wrapper) {
        background-color: rgba($color: #fff, $alpha: 75%);
      }
    }
  }

  .login_foot {
    position: fixed;
    right: 0;
    bottom: 36px;
    left: 0;
    width: 100%;
    font-size: 14px;
    font-weight: bold;
    color: #333;
    text-align: center;
  }
}
</style>
